package com.example.aop.proxy;

import org.springframework.cglib.proxy.Enhancer;

import java.lang.reflect.Proxy;

public class Main {

    public static void main(String[] args) {
        // 静态代理
        HouseProxy houseProxy = new HouseProxy(new RealHouseSubject());
        houseProxy.rentHouse();

        //无代理
        RealHouseSubject realHouseSubject = new RealHouseSubject();
        System.out.println("----------------------------");
        realHouseSubject.rentHouse();

        //JDK动态代理
        /**
         * public static Object newProxyInstance(ClassLoader loader,
         *                                       Class<?>[] interfaces,
         *                                       InvocationHandler h)
         */
        // 代理接口，代理成功
        RealHouseSubject target = new RealHouseSubject();
//        HouseSubject proxy= (HouseSubject)Proxy.newProxyInstance(
//                HouseSubject.class.getClassLoader(),
//                new Class[]{HouseSubject.class},
//                new JDKInvocationHandler(target));
//        proxy.rentHouse();
//        proxy.saleHouse();

        // 代理类，代理失败
//        RealHouseSubject proxy1 = (RealHouseSubject) Proxy.newProxyInstance(
//                HouseSubject.class.getClassLoader(),
//                new Class[]{HouseSubject.class},
//                new JDKInvocationHandler(target));
//        proxy.rentHouse();
//        proxy.saleHouse();

        //使用 CGLib代理
        /**
         *  create(Class[] argumentTypes, Object[] arguments)
         */
        // 代理接口, 代理成功
        HouseSubject houseSubject = (HouseSubject) Enhancer.create(target.getClass(), new CGLibMethodInterceptor(target));
        houseSubject.rentHouse();
        houseSubject.saleHouse();
        // 代理类，代理成功
        RealHouseSubject realHouseSubject1 = (RealHouseSubject) Enhancer.create(target.getClass(), new CGLibMethodInterceptor(target));
        houseSubject.rentHouse();
        houseSubject.saleHouse();
    }

}
